<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>监听器</title>
    <script src="script/vue-2.4.0.js"></script>
</head>

<body>
    <div id="app">
        <table>
            <tr>
                <td>{{goods.price}}</td>
                <td>
                    <button @click="sub">-</button>{{goods.quantity}}
                    <button @click="add">+</button>
                </td>
                <td>{{totalPrice}}</td>

            </tr>
        </table>
    </div>
    <script>
        Vue.config.productionTip = false //关闭生成信息提示
        var vm = new Vue({
            el: '#app',
            data: {
                //变量直接声明在data中
                // price: 399,
                // quantity: 2
                //作业中price和quantity声明在对象中good

                goods: {
                    price: 399,
                    quantity: 2
                }
            },
            methods: {
                sub() {
                    this.goods.quantity--
                },
                add() {
                    this.goods.quantity++
                },

            },
            computed: {
                totalPrice() {
                    return this.goods.price * this.goods.quantity
                }
            },
            watch: { //监听器可以定义多个，不需要监听的变量是谁？
                //newVal就是变化后数量quantity的值
                //oldVal就是变化前数量quantity的值
                /* quantity(newVal, oldVal) {
                     console.log("新" + newVal)
                     console.log("旧" + oldVal)
                     this.quantity = newVal <= 0 ? oldVal : newVal
                 }*/

                //只能监听对象goods
                goods: {
                    handler(newVal, oldVal) {
                        //监听对象的话 newVal和oldVal不是我们的数量，是你监听的对象 goods
                        //newVal和oldVal里面存储的数据都是goods这个对象，newVal和oldVal都是指向同一个对象，同一个goods
                        console.log(newVal + '---------' + oldVal)
                            //直接写1，因为取不到旧的值
                        this.goods.quantity = newVal.quantity <= 0 ? 1 : newVal.quantity
                    },
                    deep: true //对象的话，必须开启深度监听

                }
            }
        })
    </script>
</body>

</html>